<?php

namespace app\admin\controller\rate;

use app\common\controller\Backend;
use app\common\model\rate\AdminRateArea;
use app\common\model\rate\AuthGroupAccess;
use fast\Random;
use fast\Tree;
use think\Db;
use think\exception\ValidateException;
use think\Validate;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\rate\Admin();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('type', 1) //只查看税源地管理员
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->paginate($limit);


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    //修改选择所有税源地

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
                    'email'    => 'email|unique:admin,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                //判断是否加入权限组  如果没有加入  就加入默认顶级权限组
                if (AuthGroupAccess::where(['uid' => $ids, 'group_id' => config('site.rate_top_group')])->count() <= 0) {
                    //加入
                    AuthGroupAccess::create(['uid' => $ids, 'group_id' => config('site.rate_top_group')]);
                }
                //是税源地管理员
                $rate_area_list = $this->request->post("rate_area_list/a");
                $areaAll = [];
                if (!$rate_area_list) {
                    throw new ValidateException('请选择税源地');
                }
                foreach ($rate_area_list as $value) {
                    $areaAll[] =  ['admin_id' => $row['id'], 'rate_area_id' => $value];;
                    AdminRateArea::where(['admin_id' => $row['id'], 'rate_area_id' => $value])->delete();
                }

                (new AdminRateArea())->insertAll($areaAll);
                $this->success();
            }
            $this->error();
        }
        $rate =  \app\common\model\rate\Area::where('is_show' , 0)->select();
        $rate_ids = AdminRateArea::where('admin_id', $ids)->column('rate_area_id');
        $rate_area = [];
        foreach ($rate as $k => $v) {
            $rate_area[$v['id']] = $v['name'];
        }

        $this->assign('rate_area', $rate_area);
        $this->assign('rate_ids', $rate_ids);
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if (!Validate::is($params['password'], '\S{6,16}')) {
                    $this->error(__("Please input correct password"));
                }
                Db::startTrans();
                try {

                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。

                    $params['who'] = 1;
                    $params['type'] = 1;

                    $result = $this->model->validate('Admin.add')->save($params);
                    if ($result === false) {
                        throw new ValidateException($this->model->getError());
                    }

                    //如果是税源地管理员，需要记录改管理员管理那几个税源地
                    if ($params['type'] == 1) {
                        //是税源地管理员
                        $rate_area_list = $this->request->post("rate_area_list/a");
                        $areaAll = [];
                        if (!$rate_area_list) {
                            throw new ValidateException('请选择税源地');
                        }
                        foreach ($rate_area_list as $value) {
                            $areaAll[] =  ['admin_id' => $this->model->id, 'rate_area_id' => $value];;
                        }
                        //税源地中间表
                        (new AdminRateArea())->insertAll($areaAll);
                    }

                    //权限表
                    AuthGroupAccess::create(['uid' => $this->model->id, 'group_id' => config('site.rate_top_group')]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }

        $rate =  \app\common\model\rate\Area::where('is_show' , 0)->select();
        $rate_area = [];
        foreach ($rate as $k => $v) {
            $rate_area[$v['id']] = $v['name'];
        }

        $this->assign('rate_area', $rate_area);
        return $this->view->fetch();
    }

}
